<template>
  <scroll-view class="flex-col page mine" scroll-y @scroll="onPageScroll">
    <view class="flex-col section" :style="{ paddingTop: navHeight + 'px' }">
      <xlm-top-nav :scrollTop="scrollTop" title="合作赛事申请表" />
      <view class="cooperation-apply-page">
        <!-- 顶部Banner -->
        <image class="banner" :src="imgUrl + 'a.jpg'" mode="aspectFill" />

        <view class="form-card">
          <!-- 姓名 -->
          <view class="form-item">
            <view class="label required">姓名</view>
            <input class="input" v-model="form.name" placeholder="请输入" />
            <view v-if="formErrors.name" class="error-message">{{ formErrors.name }}</view>
          </view>
          <!-- 联系电话 -->
          <view class="form-item">
            <view class="label required">联系电话</view>
            <input class="input" v-model="form.phone" placeholder="请输入" />
            <view v-if="formErrors.phone" class="error-message">{{ formErrors.phone }}</view>
          </view>
          <!-- 所在地区 -->
          <view class="form-item">
            <view class="label required">所在地区</view>
            <area-picker
              :placeholder="'请选择省市区'"
              :arrow-icon="imgUrl + 'arrow-right.png'"
              :default-value="{ province: form.province, city: form.city, district: form.district }"
              @change="onAreaChange"
              @cancel="onAreaCancel"
            />
          </view>
          <!-- 希望合作赛事名称 -->
          <view class="form-item">
            <view class="label required">希望合作赛事名称</view>
            <input class="input" v-model="form.act_name" placeholder="请输入" />
            <view v-if="formErrors.act_name" class="error-message">{{ formErrors.act_name }}</view>
          </view>
          <!-- 赛事主办单位名称 -->
          <view class="form-item">
            <view class="label required">赛事主办单位名称</view>
            <input class="input" v-model="form.corporate_name" placeholder="请输入" />
            <view v-if="formErrors.corporate_name" class="error-message">{{ formErrors.corporate_name }}</view>
          </view>
          <!-- 赛事主办单位性质 -->
          <view class="form-item">
            <view class="label required">赛事主办单位性质</view>
            <view class="tag-group">
              <view v-for="(item, idx) in orgTypes" :key="item"
                :class="['tag', { active: form.company_property === item }]" @tap="form.company_property = item">{{ item
                }}</view>
            </view>
          </view>
          <!-- 希望我们为您提供服务（多选） -->
          <view class="form-item">
            <view class="label required">希望我们为您提供服务（多选）</view>
            <view class="tag-group">
              <view v-for="(item, idx) in serviceTypes" :key="item"
                :class="['tag', { active: form.service.includes(item) }]" @tap="toggleService(item)">{{ item }}</view>
            </view>
          </view>
          <!-- 详细说明 -->
          <view class="form-item">
            <view class="label required">详细说明</view>
            <textarea class="textarea" v-model="form.desc" placeholder="请输入" />
            <view v-if="formErrors.desc" class="error-message">{{ formErrors.desc }}</view>
          </view>
        </view>

        <button class="submit-btn" @tap="submit">确认提交</button>
      </view>
    </view>

  </scroll-view>
</template>

<script setup>
  import { ref, computed } from 'vue'
  import { useOutsideAppStore } from '@/store/app'
  import { imgUrl } from '@/utils/config'
  import { onShow, onLoad } from '@dcloudio/uni-app';
  import { useRequest } from '@/api';
  import { watch } from 'vue';
  import AreaPicker from '@/components/AreaPicker/index.vue'
  const { API_INDEX_AREA_POST, API_EVENT_APPLY_POST } = useRequest();
  const appStore = useOutsideAppStore()
  const navHeight = computed(() => appStore.navHeight)
  const scrollTop = ref(0)
  const onPageScroll = (e) => {
    scrollTop.value = e.detail.scrollTop
  }
  const mainId = ref(0)
  const form = ref({
    name: '',//姓名
    phone: '',//联系电话
    act_name: '',//希望合作赛事名称
    corporate_name: '',//赛事主办单位名称
    company_property: '政府机构',//赛事主办单位性质
    service: ['报名系统'],//希望我们为您提供服务（多选）
    desc: '',//详细说明
    // 地区相关
    province: '',//省
    city: '',//市
    district: '',//区
    areaText: ''//地区
  })

  // 表单校验状态
  const formErrors = ref({})

  const orgTypes = ['政府机构', '协会', '学校']
  const serviceTypes = ['报名系统', '编排', '电计', '直播', '品牌设计']

  onShow(() => {
    const pages = getCurrentPages(); // 获取当前页面栈
    const currentPage = pages[pages.length - 1]; // 获取当前页面
    console.log('currentPage', currentPage);

    const options = currentPage.options; // 获取当前页面的参数
    const { id } = options;
    console.log('id++___---', id);
    mainId.value = id;
  })

  // 省市区选择器事件处理
  function onAreaChange(areaData) {
    console.log('地区选择变化:', areaData)
    form.value.province = areaData.province_id
    form.value.city = areaData.city_id
    form.value.district = areaData.region_id
    form.value.areaText = areaData.areaText
  }

  function onAreaCancel() {
    console.log('地区选择取消')
  }

  function toggleService(item) {
    // 确保service字段存在且为数组
    if (!form.value.service) {
      form.value.service = []
    }
    
    const idx = form.value.service.indexOf(item)
    if (idx > -1) {
      form.value.service.splice(idx, 1)
    } else {
      form.value.service.push(item)
    }
  }
  function submit() {
    // 清除之前的错误状态
    formErrors.value = {}

    // 表单校验逻辑
    const validationResult = validateForm()

    if (!validationResult.isValid) {
      // 显示错误信息
      uni.showToast({
        title: validationResult.message,
        icon: 'none',
        duration: 2000
      })

      // 设置对应的错误状态
      if (validationResult.field) {
        formErrors.value[validationResult.field] = validationResult.message
      }

      return
    }

    // 校验通过，执行提交逻辑
    submitForm()
  }

  // 表单校验函数
  function validateForm() {
    const { name, phone, act_name, corporate_name, company_property, service, desc, province, city, district } = form.value

    // 1. 校验姓名
    if (!name || name.trim() === '') {
      return {
        isValid: false,
        message: '请输入姓名',
        field: 'name'
      }
    }

    if (name.trim().length < 2) {
      return {
        isValid: false,
        message: '姓名至少2个字符',
        field: 'name'
      }
    }

    // 2. 校验联系电话
    if (!phone || phone.trim() === '') {
      return {
        isValid: false,
        message: '请输入联系电话',
        field: 'phone'
      }
    }

    // 手机号格式校验
    const phoneRegex = /^1[3-9]\d{9}$/
    if (!phoneRegex.test(phone.trim())) {
      return {
        isValid: false,
        message: '请输入正确的手机号码',
        field: 'phone'
      }
    }

    // 3. 校验所在地区
    if (!province || !city || !district) {
      return {
        isValid: false,
        message: '请选择完整的所在地区',
        field: 'area'
      }
    }

    // 4. 校验希望合作赛事名称
    if (!act_name || act_name.trim() === '') {
      return {
        isValid: false,
        message: '请输入希望合作赛事名称',
        field: 'act_name'
      }
    }

    if (act_name.trim().length < 2) {
      return {
        isValid: false,
        message: '赛事名称至少2个字符',
        field: 'act_name'
      }
    }

    // 5. 校验赛事主办单位名称
    if (!corporate_name || corporate_name.trim() === '') {
      return {
        isValid: false,
        message: '请输入赛事主办单位名称',
        field: 'corporate_name'
      }
    }

    if (corporate_name.trim().length < 2) {
      return {
        isValid: false,
        message: '主办单位名称至少2个字符',
        field: 'corporate_name'
      }
    }

    // 6. 校验赛事主办单位性质
    if (!company_property || !orgTypes.includes(company_property)) {
      return {
        isValid: false,
        message: '请选择赛事主办单位性质',
        field: 'company_property'
      }
    }

    // 7. 校验希望我们为您提供服务
    if (!service || service.length === 0) {
      return {
        isValid: false,
        message: '请至少选择一项服务',
        field: 'service'
      }
    }

    // 8. 校验详细说明
    if (!desc || desc.trim() === '') {
      return {
        isValid: false,
        message: '请输入详细说明',
        field: 'desc'
      }
    }

    if (desc.trim().length < 10) {
      return {
        isValid: false,
        message: '详细说明至少10个字符',
        field: 'desc'
      }
    }

    // 所有校验通过
    return {
      isValid: true,
      message: '校验通过'
    }
  }

  // 提交表单
  async function submitForm() {
    try {

      // 构建提交数据
      const submitData = {
        id: mainId.value,
        name: form.value.name.trim(),//姓名
        mobile: form.value.phone.trim(),//联系电话
        province_id: form.value.province,//省
        city_id: form.value.city,//市
        region_id: form.value.district,//区
        address: form.value.areaText.replace(/\s+/g, ''), // 去除地址中的所有空格
        act_name: form.value.act_name.trim(),//希望合作赛事名称
        corporate_name: form.value.corporate_name.trim(),//赛事主办单位名称
        company_property: form.value.company_property,//赛事主办单位性质
        service: form.value.service && form.value.service.length > 0
          ? form.value.service.join(',')
          : '', // 希望我们为你提供的服务（多选） 英文','隔开
        desc: form.value.desc.trim()//详细说明
      }
      console.log('提交数据:', submitData)
      try {

        const res = await API_EVENT_APPLY_POST(submitData)
        console.log('API_EVENT_APPLY_POST_RES', res)

        if (res.code === 1) {
          uni.showToast({ title: '提交成功', icon: 'none' })
          resetForm();//提交成功后清空表单
          //延迟返回上一页
          setTimeout(() => {
            uni.navigateBack();
          }, 1000);
        } else {
          uni.showToast({ title: res.msg, icon: 'none' })
        }
      } catch (error) {
        uni.showToast({ title: error.message, icon: 'none' })
      }


    } catch (error) {
      uni.hideLoading()
      console.error('提交失败:', error)
      uni.showToast({
        title: error.message || '提交失败，请重试',
        icon: 'none',
        duration: 2000
      })
    }
  }

  // 重置表单
  function resetForm() {
    form.value = {
      name: '',
      phone: '',
      act_name: '',
      corporate_name: '',
      company_property: '政府机构',
      service: ['报名系统'],
      desc: '',
      province: '',
      city: '',
      district: '',
      areaText: ''
    }
  }
</script>

<style lang="scss" scoped>
  @import './index.scss';
</style>